// 导入云函数对象和store

import store from '../store';
import * as getGrid from './getSurroundingGrids';
const groupManager = uniCloud.importObject('groupManager',{customUI:true});
import { storageUtil } from './storageUtil';
import * as msgAction from '@/utils/msgAction.js';

const radius = store.state.msg.stateConfig.radius || 5;
import getFriendUserInfo from './getFriendUserInfo';

/**
 * @param {Object} list
 */
function  sortNewMsg(list){
	const topSessions = list.filter(item => item.isTop);
	const normalSessions = list.filter(item => !item.isTop)
	                              .sort((a, b) => (b.time || 0) - (a.time || 0));
								 return [...topSessions,...normalSessions]
	
}
/**
 * 公共函数：对会话列表进行排序（置顶在前，普通会话按时间倒序）
 * @param {Array} list - 待排序的会话列表
 * @returns {Array} 排序后的会话列表
 */
function sortChatList(list) {
  // 从本地存储获取数据
  const lastStore = uni.getStorageSync('lastStore') || {};
  const chatList = lastStore.chatList || [];


  // 性能优化：将需要比较的 ID 存入 Set，以 O(1) 的时间复杂度进行查找
  const groupIds = new Set(chatList.map(c => c.groupId));
  const favoriteIds = new Set(chatList.map(c => c.favorite_id));
  const userIds = new Set(chatList.map(c => c.userId));

  // 过滤列表
  const newlist = list.filter((item) => {
    // 使用 Set.has() 进行快速查找
    return groupIds.has(item.groupId) || 
           favoriteIds.has(item.favorite_id) || 
           userIds.has(item.userId)||item.unreadCount>0;
  });

  // 分离置顶和普通会话
  const topSessions = newlist.filter(item => item.isTop);
  const normalSessions = newlist.filter(item => !item.isTop)
                                .sort((a, b) => (b.time || 0) - (a.time || 0));

  // 合并并返回结果
  return [...topSessions, ...normalSessions];
}
/**
 * 根据会话ID判断该会话是否为置顶状态
 * @param {string} id - 会话ID，可以是 groupId, favorite_id 或 userId
 * @returns {boolean} - 返回 true 表示置顶，false 表示未置顶
 */
function getIsTop(id) {
  const lastStore = uni.getStorageSync('lastStore') || {};
  const { chatList = [] } = lastStore;
  const targetChat = chatList.find(item => item.groupId === id || item.favorite_id === id || item.userId === id);
  return targetChat?.isTop ?? false;
}

/**
 * 核心函数：格式化聊天列表数据（合并收藏+最近会话+群聊，统一结构）
 * @returns {Array} 格式化后的聊天列表（按“置顶+时间”排序）
 */
export async function chatFormat(lastTimeMap = new Map()){
  const viewList = [];
  try {
    const { user } = store.state.msg;
    // 1. 并行获取各类消息（失败不影响整体）
    const [favMsgsRes, groupMsgsRes, personMsgsRes] = await Promise.allSettled([
      ...(user.favorite?.map(item => msgAction.getPublicMsg(item.location)) || []),
      ...(user.groups?.map(item => msgAction.getGroupMsg(item.groupId)) || []),
      msgAction.getPersonMsg(user)
    ]);

    // 2. 处理收藏消息（修复：去掉!item.isRead，显示所有消息的会话）
    const storePublic = storageUtil.getByPrefix('msg_public');
    const uniqueFilter = uniqueByKey('timestamp');
    const uniqueMsgs = Object.values(storePublic)
      .flatMap(value => Array.isArray(value) ? value : [])
      .filter(item => uniqueFilter(item) && item.grid !== "NaN_NaN"); // 仅过滤无效网格

    for (const favorite of user.favorite || []) {
      const { location, favorite_id, name } = favorite;
      const gridCenter = getGrid.getGridCode(location);
      if (!gridCenter) {
        console.warn('当前收藏无有效location，跳过', favorite);
        continue;
      }
      // 修复：处理config.radius为undefined的情况
      const favoriteRadius = favorite.config?.radius ?? 5;
      const gridRoued = getGrid.getSurroundingGrids(gridCenter, favoriteRadius);
      const matchedMsgs = uniqueMsgs.filter(item => gridRoued.includes(item.grid));

      const { unreadCount, lastTime, lastMsg } = matchedMsgs.reduce(
        (acc, item) => {
          if (!item.isRead) acc.unreadCount++;
          const itemTime = Number(item.timestamp) || 0;
          if (itemTime > acc.lastTime) {
            acc.lastTime = itemTime;
            acc.lastMsg = item;
          }
          return acc;
        },
        { unreadCount: 0, lastTime: 0, lastMsg: null }
      );

      // 有消息就显示（已读/未读都算）
      if (lastMsg) {
        viewList.push({
          type: 'favorite',
          favorite_id: favorite_id,
          title: name || '未命名收藏',
          avatarList: [{ url: '' }], // 无头像传空
          isTop: getIsTop(favorite_id), // 正确使用收藏ID
          sendUserId: lastMsg.sendUserId,
          note: formatNote(lastMsg) || '无消息',
          time: lastTime,
          badgeText: unreadCount,
          location
        });
      }
    }

    // 3. 处理个人聊天消息（优化：增加请求失败兜底）
    const storePerson = storageUtil.getByPrefix('msg_person');
    const personEntries = Object.entries(storePerson);
    const userQueryTasks = [];
    const sessionDataList = [];

    for (const [key, chatRecords] of personEntries) {
      if (!Array.isArray(chatRecords) || chatRecords.length === 0) continue;
      const otherUserId = key.replace('msg_person_', '');
      if (!otherUserId) continue;
      sessionDataList.push({ otherUserId, chatRecords });
	  if(!otherUserId) console.warn(otherUserId);
      userQueryTasks.push(getFriendUserInfo(otherUserId));
    }

    const userInfoList = await Promise.allSettled(userQueryTasks);
    const userInfoMap = new Map();
    sessionDataList.forEach(({ otherUserId }, index) => {
      const res = userInfoList[index];
      // 优化：请求失败时兜底默认信息（无头像传空）
      if (res.status === 'fulfilled' && res.value) {
        userInfoMap.set(otherUserId, res.value);
      } else {
        userInfoMap.set(otherUserId, {
          userId: otherUserId,
          nicName: '未知联系人',
          nicPic: '' // 无头像传空
        });
      }
    });

    for (const { otherUserId, chatRecords } of sessionDataList) {
      const otherInfo = userInfoMap.get(otherUserId);
      const allLatestMsg = chatRecords.reduce((latest, curr) => {
        const currTime = Number(curr.timestamp) || 0;
        const latestTime = Number(latest.timestamp) || 0;
        return currTime > latestTime ? curr : latest;
      }, chatRecords[0]);

      const sessionLastTime = lastTimeMap.get(otherUserId) || 0;
      const unreadCount = chatRecords.filter(item =>
        item.sendUserId !== user.userId && !item.isRead && Number(item.timestamp) > sessionLastTime
      ).length;

      if (allLatestMsg) {
        viewList.push({
          type: 'person',
          userId: otherInfo.userId,
	      title: otherInfo.nicName,
          avatarList: [{ url: otherInfo.nicPic, nicName: otherInfo.nicName, userId: otherInfo.userId }],
          isTop: getIsTop(otherInfo.userId), // 正确使用用户ID
          note: formatNote(allLatestMsg),
          time: Number(allLatestMsg.timestamp) || 0,
          badgeText: unreadCount
        });
      }
    }

    // 4. 处理群聊消息（优化：增加请求失败兜底）
    const storeGroup = storageUtil.getByPrefix('msg_group');
    const groupEntries = Object.entries(storeGroup);
    const groupQueryTasks = [];
    const groupSessionDataList = [];

    for (const [key, chatRecords] of groupEntries) {
      if (!Array.isArray(chatRecords) || chatRecords.length === 0) continue;
      const groupId = key.replace('msg_group_', '');
      if (!groupId) continue;
      groupSessionDataList.push({ groupId, chatRecords });
      groupQueryTasks.push(getGroupInfo(groupId));
    }

    const groupInfoList = await Promise.allSettled(groupQueryTasks);
    const groupInfoMap = new Map();
    groupSessionDataList.forEach(({ groupId }, index) => {
      const res = groupInfoList[index];
      // 优化：请求失败时兜底默认信息（无头像传空）
      if (res.status === 'fulfilled' && res.value) {
        groupInfoMap.set(groupId, res.value);
      } else {
        groupInfoMap.set(groupId, {
          groupId: groupId,
          groupName: '未知群组',
          groupAvatar: [{ url: '' }] // 无头像传空
        });
      }
    });

    for (const { groupId, chatRecords } of groupSessionDataList) {
      const groupInfo = groupInfoMap.get(groupId);
      const allLatestMsg = chatRecords.reduce((latest, curr) => {
        const currTime = Number(curr.timestamp) || 0;
        const latestTime = Number(latest.timestamp) || 0;
        return currTime > latestTime ? curr : latest;
      }, chatRecords[0]);

      const sessionLastTime = lastTimeMap.get(`group_${groupId}`) || 0;
      const unreadCount = chatRecords.filter(item =>
        item.sendUserId !== user.userId && !item.isRead && Number(item.timestamp) > sessionLastTime
      ).length;

      if (allLatestMsg) {
        viewList.push({
          type: 'group',
          groupId: groupId,
          title: groupInfo.groupName,
          avatarList: groupInfo.groupAvatar,
          note: formatNote(allLatestMsg),
          time: Number(allLatestMsg.timestamp) || 0,
          badgeText: unreadCount,
          isTop: getIsTop(groupId), // 正确使用群ID
		  sendUserId:allLatestMsg.sendUserId
        });
      }
    }

    // 统一排序（置顶在前 + 普通会话时间倒序）
    return sortChatList(viewList);
  } catch (e) {
    console.error('chatFormat 执行失败：', e);
    return viewList;
  }
}

/**
 * 处理本地公共消息（附近消息）
 */
export function publicChat(location) {
  try {
    const grid = getGrid.getGridCode(location);
    const aroundMe = getGrid.getSurroundingGrids(grid, radius);
    const storeMsgs = storageUtil.getByPrefix('msg_public_');
    // 优化：简化消息扁平化逻辑
    const flatMsgs = Object.values(storeMsgs).flatMap(v => Array.isArray(v) ? v : [v]);
    const chatlist = flatMsgs.filter(item => aroundMe.includes(item.grid));

    if (chatlist.length === 0) {
      return {
        type: 'public',
        unreadCount: 0,
        msg: '还没有人发过信息呢...',
        latestTime: Date.now(),
        avatar: '' // 无头像传空
      };
    }

    const { unreadCount, lastMsg, latestTime } = chatlist.reduce(
      (acc, item) => {
        if (!item) return acc;
        if (!item.isRead) acc.unreadCount++;
        const msgTime = Number(item.timestamp || item.lastTime) || 0;
        if (msgTime > acc.latestTime) {
          acc.latestTime = msgTime;
          acc.lastMsg = item;
        }
        return acc;
      },
      { type: 'public', unreadCount: 0, latestTime: 0, lastMsg: null }
    );

    return {
      type: 'public',
      unreadCount,
      sendUserId: lastMsg?.sendUserId,
      msg: formatNote(lastMsg) || '无消息',
      latestTime,
      name: lastMsg?.nicName || lastMsg?.sendUserId || '公共消息',
      avatar: '' // 无头像传空
    };
  } catch (e) {
    console.error('publicChat 执行失败：', e);
    return {
      type: 'public',
      unreadCount: 0,
	  sendUserId:"",
      msg: '加载失败',
      latestTime: Date.now(),
      avatar: '' // 无头像传空
    };
  }
}

/**
 * 新增：查询群信息（优化：增加成员过滤和头像兜底）
 * @param {string} id - 群ID
 * @returns {Object} 群信息
 */
async function getGroupInfo(id) {
  try {
	  const  groupId=id

    const groupRes = await groupManager.getGroupBygroupId(store.state.msg.user.userId, {groupId});
    if (!groupRes?.code || !groupRes.data || !Array.isArray(groupRes.data.groupUser)) {
      return {groupId:id,groupName:groupRes.errMsg,groupAvatar:[{url:""}]}
    }

    // 优化：过滤无效成员ID，避免请求失败
    const userIds = groupRes.data.groupUser
      .map(user => user.userId)
      .filter(userId => userId) // 去掉undefined/null的ID
      .slice(0, 9);

    const avatarPromises = userIds.map(async (userId) => {
      try {
		  if(!userId) console.warn(userId);
        const userInfo = await getFriendUserInfo(userId);
        return { nicName: userInfo.nicName, url: userInfo.nicPic, userId: userInfo.userId };
      } catch (userErr) {
        console.error(`获取用户 ${userId} 头像失败：`, userErr);
        return { nicName: '未知成员', url: '', userId }; // 无头像传空
      }
    });

    const groupAvatar = await Promise.all(avatarPromises);
    // 兜底：无成员头像时传空数组（UI处理）
    return {
      groupId: id,
      groupName: groupRes.data.groupName || '未命名群组',
      groupAvatar: groupAvatar.length > 0 ? groupAvatar : [{ url: '' }]
    };
  } catch (e) {
    console.error(`查询群 ${id} 信息失败：`, e);
    return { groupId: id, groupName: '未知群组', groupAvatar: [{ url: '' }] }; // 无头像传空
  }
}

/**
 * 格式化消息内容
 * @param {Object} item - 消息对象
 * @returns {String} 格式化后的文本
 */
export function formatNote(item) {
  if (!item) return '暂无消息记录';
  const msgType = item.messageType;
  const msgMap = {
    3: '发了图片信息',
    2: item.content?.text || '文本消息',
    1: '发了语音信息',
    6: '分享了视频信息',
    4: '分享商品信息',
    5: '分享商业信息',
    8: '分享了位置',
    9: '入群邀请',
    7: '申请加好友'
  };
  return msgMap[msgType] || '收到一条新消息';
}

/**
 * 按唯一字段去重的过滤函数
 * @param {string} key - 唯一标识字段
 * @returns {Function} filter回调函数
 */
function uniqueByKey(key) {
  const map = new Map();
  return item => {
    const value = item?.[key];
    if (value === undefined || map.has(value)) return false;
    map.set(value, true);
    return true;
  };
}

/**
 * 处理新消息，更新会话列表（修复：isTop判断+排序逻辑）
 * @param {Object} newMsg - 新消息
 * @param {Array} chatList - 旧的会话列表
 * @returns {Array} 更新后的会话列表
 */
export async function newMsg(newMsg, chatList) {
	console.log("新消息处理",newMsg);
  if (!newMsg || !newMsg.toTarget || !Array.isArray(chatList)) {
    console.warn('newMsg 结构不完整或 chatList 无效');
    return chatList || [];
  }

  let newList = [...chatList];
  const { targetType } = newMsg.toTarget;
  const currentUserId = store.state.msg.user?.userId;
  const isSelfSend = newMsg.sendUserId === currentUserId;

  try {
    const baseChat = {
      type: 'favorite',
      title: '',
      sendUserId: '',
      groupId: '',
      favorite_id: '',
      note: '',
      time: '',
      badgeText: 0,
      location: '',
      avatarList: [{ url: '' }] // 无默认头像，传空
    };

    // 场景1：收藏相关消息
    if (targetType === '1') {
      const grid = newMsg.grid;
      if (!grid) return newList;
      const res = isInFavorite(grid);
      if (res?.code) {
        const { favorite_id, name, avatar, location } = res.favorite;
        const idx = newList.findIndex(item => item.type === 'favorite' && item.favorite_id === favorite_id);
        
        if (idx !== -1) {
          // 更新已有会话（修复：用res.favorite.favorite_id判断isTop）
          newList[idx] = {
            ...newList[idx],
			sendUserId:newMsg.sendUserId,
	        note: formatNote(newMsg),
            badgeText: isSelfSend ? newList[idx].badgeText : (newList[idx].badgeText || 0) + 1,
            time: newMsg.timestamp,
            isTop: getIsTop(favorite_id)
          };
        } else {
          // 新增会话（修复：用收藏ID判断isTop）
          const newChat = {
            ...baseChat,
            type: 'favorite',
            note: formatNote(newMsg),
            time: newMsg.timestamp,
            badgeText: isSelfSend ? 0 : 1,
            title: name || '未命名',
            favorite_id,
			sendUserId:newMsg.sendUserId,
            location,
            avatarList: [{ url: avatar || '' }], // 无头像传空
            isTop: getIsTop(favorite_id)
          };
          newList.push(newChat); // 先添加，最后统一排序
        }
      }
    }

    // 场景2：群聊消息（修复：拼写错误gorupId→groupId）
    else if (targetType === '2') {
      const groupId = newMsg.toTarget.targetId;
      if (!groupId) return newList;

      let groupName = '';
      let groupAvatar =[{ url: '' }]; // 无头像传空
      if (!newMsg.groupName || !newMsg.groupAvatar) {
        const groupInfo = await getGroupInfo(groupId);
        groupName = groupInfo.groupName;
        groupAvatar = groupInfo.groupAvatar;
      }

      const idx = newList.findIndex(item => item.type === 'group' && item.groupId === groupId);
      if (idx !== -1) {
        // 更新已有会话（修复：拼写错误）
        newList[idx] = {
          ...newList[idx],
          title: groupName,
		  sendUserId:newMsg.sendUserId,
          avatarList: groupAvatar,
          note: formatNote(newMsg),
          time: newMsg.timestamp,
          badgeText: isSelfSend ? newList[idx].badgeText : (newList[idx].badgeText || 0) + 1,
          isTop: getIsTop(groupId)
        };
      } else {
        // 新增会话（修复：拼写错误）
        const newSession = {
          ...baseChat,
          type: 'group',
          groupId: groupId,
		  sendUserId:newMsg.sendUserId,
          title: groupName,
          avatarList: groupAvatar,
          note: formatNote(newMsg),
          time: newMsg.timestamp,
          badgeText: isSelfSend ? 0 : 1,
          isTop: getIsTop(groupId)
        };
        newList.push(newSession); // 先添加，最后统一排序
      }
    }

    // 场景3：个人聊天消息（修复：多传参数+排序逻辑）
    else if (targetType === '3') {
      let userId, avatarList, title, isTop;
      if (isSelfSend) {
        const targetId = newMsg.toTarget.targetId;
        if (!targetId) return newList;
        // 修复：getFriendUserInfo只传targetId（原多传了newMsg.sendUserId）
		console.warn(targetId);
        const res = await getFriendUserInfo(targetId);
		console.log("查询到的用户",res);
        userId = targetId;
	
        avatarList = [{ url: res?.nicPic || '', nicName: res?.nicName || '', userId: res?.userId }]; // 无头像传空
        isTop = getIsTop(targetId);
        title = res?.nicName || '匿名用户';
      } else {
        userId = newMsg.sendUserId;
	
        avatarList = [{ url: newMsg.nicPic?.url || '', nicName: newMsg.nicName, userId: userId }]; // 无头像传空
        isTop = getIsTop(userId);
        title = newMsg.nicName || '匿名用户';
      }
if (userId === currentUserId) return newList;
      const idx = newList.findIndex(item => item.type === 'person' && item.userId === userId);
      if (idx !== -1) {
        // 更新已有会话
        newList[idx] = {
          ...newList[idx],
          title,
          isTop,
		  sendUserId:newMsg.sendUserId,
          avatarList,
          note: formatNote(newMsg),
          time: newMsg.timestamp,
          badgeText: isSelfSend ? newList[idx].badgeText : (newList[idx].badgeText || 0) + 1,
          location: newList[idx].location || newMsg.location
        };
      } else {
        // 新增会话
        const newSession = {
          ...baseChat,
          type: 'person',
          userId,
          title,
		  sendUserId:newMsg.sendUserId,
          isTop,
          avatarList,
          note: formatNote(newMsg),
          time: newMsg.timestamp,
          badgeText: isSelfSend ? 0 : 1,
          location: newMsg.location || {}
        };
        newList.push(newSession); // 先添加，最后统一排序
      }
    } else {
      console.warn('未处理的消息类型：', targetType);
    }

    // 统一排序（修复：所有场景都排序，确保置顶和时间顺序正确）
    return sortNewMsg(newList);
  } catch (e) {
    console.error('处理新消息失败：', e);
    return chatList;
  }
}

/**
 * 判断网格是否在收藏范围内（修复：favorites默认值）
 * @param {string} grid - 网格码
 * @returns {Object|null} 收藏信息
 */
function isInFavorite(grid) {
  const favorites = store.state.msg.user?.favorite || []; // 修复：默认值为空数组
  for (const favorite of favorites) {
    const centerGrid = getGrid.getGridCode(favorite.location);
    if (!centerGrid) continue;
    const favoriteRadius = favorite.config?.radius ?? 5;
    const roundMe = getGrid.getSurroundingGrids(centerGrid, favoriteRadius);
    if (roundMe.includes(grid)) {
      return { code: true, favorite: favorite };
    }
  }
  return null; // 明确返回null，避免undefined
}

/**
 * 新消息是否是本地公共消息
 * @param {Object} newMsg - 新消息
 * @param {Object} publicChat - 公共聊天对象
 * @returns {Object} 公共聊天对象
 */
export function setLocationPublicMsg(newMsg, publicChat) {
  try {
    const location = store.state.msg.location;
    const centGrid = getGrid.getGridCode(location);
    const roundMe = getGrid.getSurroundingGrids(centGrid, radius);
    const currentUserId = store.state.msg.user?.userId;
    const isSelfSend = newMsg?.sendUserId === currentUserId;

    let chatItem = {
      type: 'public',
      unreadCount: publicChat?.unreadCount || 0,
      msg: publicChat?.msg || '',
      latestTime: publicChat?.latestTime || 0,
      avatar: publicChat?.avatar || '', // 无头像传空
	  sendUserId:newMsg.sendUserId,
    };

    if (newMsg?.toTarget?.targetType === '1' && roundMe.some(item => item === newMsg.grid)) {
      chatItem = {
        ...chatItem,
        unreadCount: isSelfSend ? chatItem.unreadCount : (chatItem.unreadCount || 0) + 1,
        msg: formatNote(newMsg),
        latestTime: newMsg.timestamp || Date.now(),
		sendUserId:newMsg.sendUserId,
      };
    }
    return chatItem;
  } catch (e) {
    console.error('Error in setLocationPublicMsg:', e);
    return {
      type: 'public',
      unreadCount: 0,
	 sendUserId:newMsg.sendUserId,
      msg: '',
      latestTime: 0,
      avatar: '' // 无头像传空
    };
  }
}

/**
 * 合并两个会话列表
 * @param {Array} arr1 - 旧列表
 * @param {Array} arr2 - 新列表
 * @returns {Array} 合并后的列表
 */
export function chatView(arr1, arr2) {
  const typeKeyMap = {
    favorite: 'favorite_id',
    person: 'userId',
    group: 'groupId'
  };

  const resultMap = new Map();
  // 先合并旧列表
  for (const item of arr1) {
    const uniqueKey = typeKeyMap[item.type];
    if (uniqueKey && item[uniqueKey] !== undefined) {
      const identifier = `${item.type}-${item[uniqueKey]}`;
      resultMap.set(identifier, item);
    }
  }
  // 用新列表覆盖旧列表（新消息优先级高）
  for (const item of arr2) {
    const uniqueKey = typeKeyMap[item.type];
    if (uniqueKey && item[uniqueKey] !== undefined) {
      const identifier = `${item.type}-${item[uniqueKey]}`;
      resultMap.set(identifier, item);
    }
  }
  // 合并后排序
  return sortChatList(Array.from(resultMap.values()));
}

